package file

import (
	"errors"
	"io/ioutil"
	"mime/multipart"
	"os"
	"path"
)

//GetSize
func GetSize(f multipart.File) (int, error) {
	content, err := ioutil.ReadAll(f)
	return len(content), err
}

//GetExt get file ext
func GetExt(fileName string) string {
	return path.Ext(fileName)
}

//checkNotExists
func CheckNotExists(src string) bool {
	_, err := os.Stat(src)
	return os.IsNotExist(err)
}

//校验权限
func CheckPermission(src string) bool {
	_, err := os.Stat(src)
	return os.IsPermission(err)
}

// MkDir create a directory
func MkDir(src string) error {
	err := os.MkdirAll(src, os.ModePerm)
	if err != nil {
		return err
	}

	return nil
}

//create a directory if it does not exist
func IsNotExistsMkDir(src string) error {
	if notExists := CheckNotExists(src); notExists {
		if err := MkDir(src); err != nil {
			return err
		}
	}
	return nil
}

//open a file according to a specific perm
func OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
	f, err := os.OpenFile(name, flag, perm)
	if err != nil {
		return nil, err
	}
	return f, nil
}

// MustOpen maximize trying to open the file
func MustOpen(fileName, filePath string) (*os.File, error) {
	dir, err := os.Getwd()
	if err != nil {
		return nil, err
	}
	src := dir + "/" + filePath
	perm := CheckPermission(src)
	if perm {
		return nil, errors.New("file.CheckPermission denied,src:" + src)
	}
	err = IsNotExistsMkDir(src)
	if err != nil {
		return nil, err
	}
	f, err := OpenFile(src+fileName, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
	if err != nil {
		return nil, err
	}
	return f, nil
}
